package com.carsa.blackberry.ui.screen;

import java.util.Enumeration;
import java.util.Vector;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.FocusChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;

import com.carsa.blackberry.CarsaApp;
import com.carsa.blackberry.MainKeys;
import com.carsa.blackberry.domain.dto.DriverDTO;
import com.carsa.blackberry.domain.dto.DriversQueueDTO;
import com.carsa.blackberry.domain.services.impl.EntregasServiceImpl;
import com.carsa.blackberry.domain.services.impl.GenericServiceImpl;
import com.carsa.blackberry.ui.UIKeys;
import com.carsa.blackberry.ui.screen.common.BasicScreen;
import com.carsa.blackberry.util.ui.UIUtil;
import com.carsa.blackberry.util.ui.widget.GridFieldManager;

/**
 * @author Nahuel Barrios.
 * @since 19/07/2010.
 * @version 1.0
 */
public class LoginScreen extends BasicScreen {

    private BasicEditField     _ef_legajo;
    private ObjectChoiceField  _combo_userName;
    private ButtonField        _bf_login;
    private GenericServiceImpl _basicService = new GenericServiceImpl();
    
    private String _ayudanteName;

    // private LegajosServiceImpl _legajosService= new LegajosServiceImpl();

    public LoginScreen() {
	super(UIKeys.TITLE_ENTREGAS);
	super.customizeScreen();

	final BitmapField img_megatone = new BitmapField(Bitmap.getBitmapResource(UIKeys.IMG_MEGATONE_ICON_AND_TEXT),
	        FIELD_LEFT | FIELD_VCENTER);
	final BitmapField img_carsa = new BitmapField(Bitmap.getBitmapResource(UIKeys.IMG_GRUPO_CARSA_ICON_SMALL),
	        FIELD_RIGHT);
	GridFieldManager grid_top = new GridFieldManager(new int[] { 260, 60 }, 0);
	grid_top.add(img_megatone);
	grid_top.add(img_carsa);

	GridFieldManager grid_legajo = new GridFieldManager(new int[] { 200, 120 }, 0);
	grid_legajo.add(new LabelField(UIKeys.FIELD_LEGAJO_DEL_AYUDANTE));
	_ef_legajo = new BasicEditField("", "", UIKeys.SIZE_MAXIMUM_CHARACTERS_FOR_LEGAJO, EditField.FILTER_INTEGER
	        | FIELD_RIGHT);
	_ef_legajo.setFocusListener(new FocusChangeListener() {
	    public void focusChanged(Field field, int eventType) {
		if (eventType == FocusChangeListener.FOCUS_LOST) {
		    String legajo = _ef_legajo.getText();
		    if (legajo.equals(""))
			Dialog.alert(UIKeys.ERROR_LEGAJO_ES_OBLIGATORIO);
		    else {
			DriverDTO helper = _basicService.validateLegajoAyudante(legajo);
			if (helper == null){
			    Dialog.alert(UIKeys.ERROR_LEGAJO_INCORRECTO);
			    _ef_legajo.setFocus();
			}
			else{
			    _ayudanteName= helper.getFullName();
			    _combo_userName.setChoices(filterDriversFor(helper.getLegajo()));
			}
		    }
		}
	    }
	});
	grid_legajo.add(_ef_legajo);

	GridFieldManager grid_userName = new GridFieldManager(new int[] { 180, 140 }, 0);
	grid_userName.add(new LabelField(UIKeys.FIELD_NOMBRE_CHOFER));

	_combo_userName = new ObjectChoiceField("", filterDriversFor(null));
	grid_userName.add(_combo_userName);

	_bf_login = new ButtonField(UIKeys.TITLE_LOGIN, Field.FIELD_HCENTER);
	_bf_login.setFont(this.getFont().getFontFamily().getFont(Font.PLAIN, 21));
	_bf_login.setChangeListener(new FieldChangeListener() {
	    public void fieldChanged(Field field, int context) {
		if (doBeforeLeaveScreen())
		    UiApplication.getUiApplication().pushScreen(new MainMenuScreen());
	    }
	});

	// ---------------------------------------------------
	// Con todos los controles ya seteados, armo la vista.
	_mainManager.add(grid_top);

	UIUtil.addNewEmptyLine(_mainManager, 2);

	_mainManager.add(new SeparatorField());
	_mainManager.add(grid_legajo);
	_mainManager.add(new SeparatorField());
	_mainManager.add(grid_userName);
	_mainManager.add(new SeparatorField());

	UIUtil.addNewEmptyLine(_mainManager, 2);
	_mainManager.add(_bf_login);
	UIUtil.addNewEmptyLine(_mainManager, 2);
	this.add(_mainManager);
    }

    public boolean onClose() {
	return false;
    }

    public Object[] filterDriversFor(String legajoAyudante) {
	DriversQueueDTO legajos = (DriversQueueDTO) CarsaApp.getMemory().get(MainKeys.PARAMETER_LEGAJOS);

	Vector filtered = null;
	if (legajoAyudante != null)
	    filtered = legajos.getDriversFromSameZone(legajoAyudante);

	if (legajoAyudante == null || filtered.isEmpty())
	    filtered = legajos.getOnlyDrivers();

	Object[] driversName = new Object[filtered.size()];

	Enumeration elements = filtered.elements();
	for (int idx = 0; elements.hasMoreElements(); idx++) {
	    DriverDTO unLegajo = (DriverDTO) elements.nextElement();
	    driversName[idx] = unLegajo.getFullName() + " (" + unLegajo.getLegajo() + ")";
	}

	return driversName;
    }

    protected boolean doBeforeLeaveScreen() {
	String legajo = _ef_legajo.getText();

	if (legajo.equals("")) {
	    Dialog.alert(UIKeys.ERROR_LEGAJO_ES_OBLIGATORIO);
	    return false;
	}

	String nameAndLegajo = (String) _combo_userName.getChoice(_combo_userName.getSelectedIndex());
	int breakpoint = nameAndLegajo.indexOf("(") + 1;
	nameAndLegajo = nameAndLegajo.substring(breakpoint);
	nameAndLegajo = nameAndLegajo.substring(0, nameAndLegajo.indexOf(")"));

	CarsaApp.getMemory().put(MainKeys.PARAMETER_LEGAJO_DRIVER, nameAndLegajo);
	CarsaApp.getMemory().put(MainKeys.PARAMETER_LEGAJO_AYUDANTE, _ef_legajo.getText());
	CarsaApp.getMemory().put(MainKeys.PARAMETER_DRIVER_NAME,
	        _combo_userName.getChoice(_combo_userName.getSelectedIndex()));
	CarsaApp.getMemory().put(MainKeys.PARAMETER_AYUDANTE_NAME, _ayudanteName + " (" + _ef_legajo.getText() + ")");

	CarsaApp.getMemory().put(MainKeys.PARAMETER_REASONS_AND_SUBREASONS, _basicService.fetchMotivos());
	CarsaApp.getMemory().put(MainKeys.PARAMETER_PENDING_QUEUE, new EntregasServiceImpl().getEntregasQueue());
	CarsaApp.getMemory().put(MainKeys.PARAMETER_ENTREGAS_HISTORY, new EntregasServiceImpl().getEntregasHistory());

	UiApplication.getUiApplication().popScreen(this);
	return true;
    }
}
